import type { DirectiveBinding, Directive } from "vue";

const throttle: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    let timer: ReturnType<typeof setTimeout> | null = null;
    const delay = Number(binding.arg) || 1000;

    const handler = binding.value;
    if (typeof handler !== "function") {
      console.warn("v-throttle 指令绑定值必须是函数");
      return;
    }

    el.addEventListener("click", () => {
      if (!timer) {
        handler();
        timer = setTimeout(() => {
          timer = null;
        }, delay);
      }
    });
  },

  beforeUnmount(el: HTMLElement) {
    // 清除事件绑定（可选）
    el.onclick = null;
  }
};

export default throttle;
